import React, { useRef, useState, ReactText } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType } from '@ant-design/pro-table';
import { getMenuList, menuDelete } from '@/services/system/menu';
import { Spin, Switch, Popconfirm, Button, message } from 'antd';
import Search from 'antd/lib/input/Search';
import SysIcon from '@/pages/common/SysIcon';
import Tag from 'antd/es/tag';
import MenuAdd from '@/pages/system/menu/components/MenuAdd';
import MenuEdit from '@/pages/system/menu/components/MenuEdit';
import { DeleteOutlined, PullRequestOutlined } from '@ant-design/icons';

/**
 * 菜单管理
 *
 * @author zhangby
 * @date 22/9/20 5:00 pm
 */
export default (): React.ReactNode => {
  const [rows, setRows] = useState<ReactText[]>([]);
  const [loading, setLoading] = useState(false);
  const [query, setQuery] = useState<string>('');
  const [expandRow, setExpandRow] = useState<string[]>([]);

  const ref = useRef<ActionType>();

  // 搜索
  const onSearch = (val: string) => {
    setQuery(val);
    ref.current?.reload();
  };

  // 删除
  const onDelete = async (id: string) => {
    try {
      setLoading(true);
      await menuDelete(id);
      setLoading(false);
      message.success('删除记录成功！');
      // 刷新
      ref.current?.reloadAndRest();
    } catch (e) {
      setLoading(false);
    }
  };

  // 批量删除
  const onBatchDelete = () => {
    if (rows.length === 0) {
      message.error('请选择要操作的记录');
    }
    onDelete(rows.join(','));
  };

  return (
    <>
      <Spin spinning={loading}>
        <PageContainer
          subTitle="系统菜单管理"
          extra={[
            <span key="del">
              {rows.length > 0 ? (
                <Popconfirm
                  title="确定要删除选中的记录吗?"
                  onConfirm={onBatchDelete}
                  okText="Yes"
                  cancelText="No"
                >
                  <Button type="primary" danger>
                    <DeleteOutlined />
                    批量删除
                  </Button>
                </Popconfirm>
              ) : null}
            </span>,
            <MenuAdd refresh={() => ref.current?.reload()} key="add" />,
          ]}
        >
          <ProTable<System.SysMenu>
            actionRef={ref}
            search={false}
            columns={[
              {
                title: '菜单名称',
                dataIndex: 'name',
                width: 150,
                hideInSearch: true,
                render: (_, record) => (
                  <MenuEdit id={record.id} refresh={() => ref.current?.reload()}>
                    <Button type="link">{record.name}</Button>
                  </MenuEdit>
                ),
              },
              {
                title: '地址',
                dataIndex: 'href',
                width: 180,
                hideInSearch: true,
                render: (item, _) => <Tag>{item}</Tag>,
              },
              {
                title: '图标',
                dataIndex: 'icon',
                width: 80,
                hideInSearch: true,
                render: (_, record) => <SysIcon type={record.icon} />,
              },
              {
                title: '排序',
                dataIndex: 'sort',
                width: 80,
                hideInSearch: true,
              },
              {
                title: '隐藏',
                dataIndex: 'isShow',
                width: 80,
                hideInSearch: true,
                render: (item, _) => <Switch size="small" checked={item === '1'} />,
              },
              {
                title: '授权',
                dataIndex: 'permission',
                width: 150,
                hideInSearch: true,
              },
              {
                title: '操作',
                dataIndex: 'option',
                valueType: 'option',
                align: 'center',
                width: 180,
                render: (_, record) => (
                  <>
                    <MenuAdd
                      parentId={record.id}
                      parentName={record.name}
                      refresh={() => ref.current?.reload()}
                    >
                      <Button type="primary" shape="circle">
                        <PullRequestOutlined />
                      </Button>
                    </MenuAdd>
                    <Popconfirm
                      placement="topRight"
                      title="确定要删除选中的记录吗?"
                      onConfirm={() => onDelete(record.id)}
                      okText="Yes"
                      cancelText="No"
                    >
                      <Button type="primary" shape="circle" danger style={{ marginLeft: 10 }}>
                        <DeleteOutlined />
                      </Button>
                    </Popconfirm>
                  </>
                ),
              },
            ]}
            // 选择
            rowSelection={{
              columnWidth: 20,
              onChange: (selectedRowKeys, _) => setRows(selectedRowKeys),
            }}
            // 展开行配置
            expandable={{
              indentSize: 20,
              expandedRowKeys: expandRow,
              onExpandedRowsChange: (expands: string[]) => setExpandRow(expands),
            }}
            request={(params, sorter, filter) =>
              getMenuList({ ...{ ...params, keyword: query }, sorter, filter })
            }
            onLoad={(dataSource: System.SysMenu[]) => {
              setExpandRow(dataSource.map((item) => item.id));
            }}
            pagination={{
              pageSize: 10,
            }}
            rowKey="id"
            headerTitle="菜单列表"
            toolBarRender={() => [
              <Search
                placeholder="搜索"
                onSearch={(val) => onSearch(val)}
                style={{ minWidth: 400 }}
                enterButton
              />,
            ]}
          />
        </PageContainer>
      </Spin>
    </>
  );
};
